import * as requestIp from 'request-ip';
/**
 * 获取IP地址
 */
export class GetIp {
  /**
   * @desc 获得外网IP
   * @param
   * @return
   */
  static getIpData(req: any) {
    let remoteIp = requestIp.getClientIp(req) || '';
    if (remoteIp.indexOf('ffff') > 0) {
      remoteIp = remoteIp.split(':')[3];
    }
    let remoteAddress = req.connection.remoteAddress || '';
    if (remoteAddress.indexOf('ffff') > 0) {
      remoteAddress = remoteAddress.split(':')[3];
    }
    let forwarded = req.headers['x-forwarded-for'] || '';
    if (forwarded.indexOf('ffff') > 0) {
      forwarded = forwarded.split(':')[3];
    }
    const IpAddress = remoteIp || remoteAddress || forwarded;
    return IpAddress;
  }

  /**
   * @desc 获得socket请求IP地址
   * @param
   * @return
   */
  static getSocketIpData(client: any) {
    let ipAddress =
      client.handshake.address ||
      client.client.conn.remoteAddress ||
      client.request.connection.remoteAddress;
    if (ipAddress) {
      ipAddress = ipAddress.split(':')[3];
    }
    return ipAddress;
  }
}
